import axios from 'axios'
import QS from 'qs'
import { interceptResponse, showMessage } from './common'
import router from '../router'
import { Message } from "element-ui";


// 自动切换环境
// if (process.env.NODE_ENV == 'development'){
//     // axios.defaults.baseURL = '/api';
//     // axios.defaults.baseURL = 'http://meeting-front.hunterslab.cn';
// } else if (process.env.NODE_ENV == 'debug'){
//     // axios.defaults.baseURL = '/api';
// } else if (process.env.NODE_ENV == 'production') {
//     axios.defaults.baseURL = 'http://10.122.17.77/';
// }
// axios.defaults.baseURL = 'http://10.58.85.203:8083'

//设置超时时间
axios.defaults.timeout = 60000
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

axios.interceptors.request.use(
  (config) => {
    console.log(config)
    if (localStorage.getItem('tok')) {
      config.headers.common['token'] = localStorage.getItem('tok')
    }

    return config
  },
  (error) => {
    //对请求错误做什么
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  function (response) {
    // if(response.data){
    //   if(response.data.success){
    //     return response;
    //   } else if(response.data.size){
    //     return response;
    //   }else {
    //     showMessage(response.data.message)
    //   }
    // } else{
      console.log(response,444);
    return response
    // }
  },
  function (error) {
    console.log(error)
    // Message.error('存在未分配检验员的检测项目！')
    if (error && error.response) {
      
      switch (error.response.status) {
        case 403:
          router.replace({
            path: '/login',
            query: { refresh: true },
          })
          localStorage.removeItem("tok")
          break
        case 413:
         Message.error(error+',文件上传失败')
          break
        case 500:
          if(error.response.data.message=="token已失效，请重新登录"){
            router.replace({
              path: '/login',
              query: { refresh: true },
            })
            localStorage.removeItem("tok")
          }else{
            // 注释alert弹窗
            // alert(error.response.data.message.length)
            if(error.response.data.message.length!=0){
              showMessage(error.response.data.message, true)
            }
            
          }
          break

        case 501:
          error.message = '服务未实现！'
          break
          

        case 502:
          error.message = '服务器网关错误，请刷新页面或重试操作！'
          break

        case 503:
          error.message = '服务暂时不可用，请稍后重试！'
          break

        case 504:
          error.message = '服务器网关超时，请刷新页面或重试操作！'
          break

        case 505:
          error.message = 'HTTP版本不受支持！'
          break
        default:
      }
      // showMessage(error.message);
    }
  }
)

//对外接口
export function request({
  method,
  url,
  params,
  contentType,
  response,
  header,
  variable
}) {
  if (method == 'get') {
    return get(url, params, contentType, response)
  } else if (method == 'post') {
    return post(url, params, contentType, header)
  } else if (method == 'post2') {
    return post2(url, params, contentType)
  }else if (method == 'post3') {
    return post3(url, params, contentType)
  } else if (method == 'multipartPost') {
    console.log(url, params, variable)
    return multipartPost(url, params,variable)
  } else if (method == 'getBlob') {
    return getBlob(url, params)
  } else if (method == 'postBlob') {
    return postBlob(url, params)
  }
}

// 封装get方法
function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, { params: params })
      .then((res) => {
        resolve(interceptResponse(res.data))
      })
      .catch((err) => {
        reject(err)
      })
  })
}
// 封装get下载文件流方法
function getBlob(url, params) {
  return new Promise((resolve, reject) => {
    axios({ method: 'get', url, params, responseType: 'blob' })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

// 封装get下载文件流方法 dirty
function postBlob(url, params) {
  return new Promise((resolve, reject) => {
    axios({ method: 'post', url, data: params, responseType: 'blob' })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

let config = {
  headers: { 'Content-Type': 'multipart/form-data' },
}
function multipartPost(url, params,variable) { 
  let config = {
    headers: { 'Content-Type': 'multipart/form-data' },
    onUploadProgress:function(progressEvent){
        // console.log(progressEvent.loaded / progressEvent.total * 100)
        if(progressEvent.lengthComputable){
          // variable = progressEvent.loaded / progressEvent.total * 100
          return variable(progressEvent.loaded / progressEvent.total * 100)
        }
      }
  }
  return new Promise((resolve, reject) => {
    axios
      .post(url, params, config)
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        console.log(err)
        reject(err.data)

      })
  })
}

// 封装post方法
function post(
  url,
  params,
  contentType,
  header = 'application/x-www-form-urlencoded'
) {
  let data
  switch (contentType) {
    case 'json':
      data = JSON.stringify(params)
      break
    case 'multipart':
      data = params
      break
    case 'url':
      data = params.params
      break
    default:
      data = QS.stringify(params)
      break
  }
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, { headers: { 'Content-Type': header } })
      .then((res) => {
        resolve(interceptResponse(res.data))
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}

function post2(url, params, contentType) {
  let data
  switch (contentType) {
    case 'json':
      data = JSON.stringify(params)
      break
    case 'multipart':
      data = params
      break
    case 'url':
      data = params.params
      break
    default:
      data = params
      break
  }
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, { headers: { 'Content-Type': 'application/json' } })
      .then((res) => {
        resolve(interceptResponse(res.data))
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}
function post3(url, params, contentType) {
  let data
  switch (contentType) {
    case 'json':
      data = JSON.stringify(params)
      break
    case 'multipart':
      data = params
      break
    case 'url':
      data = params.params
      break
    default:
      data = params
      break
  }
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, { headers: { 'Content-Type': 'multipart/form-data' } })
      .then((res) => {
        resolve(interceptResponse(res.data))
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}
